<?php

$packages = update_package::liste();
$sources = db()->query('SELECT * FROM update_server')->assocs('id');

if( file_exists( 'inc/ftp.config.php' )) {
	require_once 'inc/ftp.config.php';
	$writer = new writer_ftp( $ftp_host, $ftp_user, $ftp_pass, $ftp_dir );
} else {
	$writer = new writer_fs();
}

if( !empty( $_GET['edit'] )) {
	if( empty( $packages[$_GET['edit']] ))
		throw new Exception( 'Paket nicht gefunden!' );
	new update_manager( $view, $packages[$_GET['edit']] );
} elseif( isset( $_GET['storefile'] )) {
	$pkg = new update_package(array( 'id' => $_POST['pkg'] ));
	$pkg->updateFile( $_POST['path'], $_POST['content'] );
	$view->plain('ok');
} elseif( isset( $_GET['addpackage'] )) {
	$pkg = new update_package( $_POST );
	$pkg->install( $writer );
	$view->plain('ok');
} elseif( isset( $_GET['getmigrations'] )) {
	$all = globFiles('migration/*');
	$applied = db()->select('update_migration')->assocs('id');
	$result = $pending =array();

	foreach( $all as $id )
		if( empty( $applied[$id] ))
			$pending[] = $id;

	$view->plain(json_encode( $pending ));
} elseif( !empty( $_GET['install'] )) {
	$view->format = 'plain';
	$migrations = new update_migration();
	$migrations->install( $_GET['install'] );
} else {
	$view->js('assets/js/update.js');
	$view->js('assets/js/migration.js');
	$view->content(template('iv.packages.install')->render( array(
		'sources' => $sources,
		'packages' => array_values( $packages )
	)));
}


